<template>
  <div class="edit">
      <van-nav-bar
        title="编辑资料"
        left-arrow
        @click-left="$router.back()"
        @click-right="$router.push({path:'/'})"
      >
         <template #right>
           <van-icon name="wap-home-o" color="red" size="6vw" />
         </template>
      </van-nav-bar>
      <div class="avatar">
          <div class="avatar-img">
              
                 <van-image
                   width="100%"
                   height="100%"
                   round
                   fit="cover"
                   :src="userinfo.head_img"
                 />
               
          </div>
          <van-uploader :after-read="afterRead" ></van-uploader>
      </div>
      <MyCell
         title="昵称"
         :value="userinfo.nickname"
         @click="nicknameShow=true"
      ></MyCell>
      <MyCell 
         title="密码"
         value="******" 
         @click=" passwordShow = true; passwordNew = ''; passwordOld = '' "
      ></MyCell>
      <MyCell 
         title="性别" 
         :value="userinfo.gender?'男':'女'" 
         @click="generShow=true"
      ></MyCell>
       <van-dialog
          v-model="nicknameShow"
          title="修改昵称"
          show-cancel-button
          @confirm="nicknameFn"
         >
      <!-- 记得在 main 里面导入表单结构 -->
      <van-field
        required
        v-model="nicknameTemp"
        label="昵称:"
        placeholder="请输入用户名"
      />
    </van-dialog>
    <!-- 修改密码的模态框 -->
    <van-dialog
      v-model="passwordShow"
      title="修改密码"
      type="password"
      show-cancel-button
      @confirm="passwordFn"
      :before-close="beforeClose"
    >
      <van-field
        required
        v-model="passwordOld"
        label="原密码"
        placeholder="请输入原密码"
      />
      <van-field
        required
        v-model="passwordNew"
        label="新密码"
        placeholder="请输入新密码"
      />
    </van-dialog>
    <!--  -->
    <van-action-sheet
      v-model="generShow"
      :actions="[{ name: '男',gender:1 }, { name: '女',gender:0 },]"
      cancel-text="取消"
      close-on-click-action
      @select="genderFn"
    />
  </div>
</template>

<script>
// this.$router.back() 可以现实返回
import MyCell from'../components/MyCell.vue'
import requser from '../utils/request'
import {userDetailAPL,userUpdateByIdAPL} from '../apis/user'
import {uploadFileAPL} from '../apis/index'
export default {
   components: {
       MyCell
   },
   data () {
       return {
           userinfo:{},
           nicknameShow: false,
           nicknameTemp: "",
           passwordShow: false,
           passwordOld:'',
           passwordNew:'',
           generShow:false,
       }
   },
   async created () {
     const id=this.$route.query.id
     if(!id)return this.$toast.fail('没有用户id')
     const res = await userDetailAPL(id)
     console.log(res)
    //   拼接后在复制给自己
      res.data.data.head_img=requser.defaults.baseURL+res.data.data.head_img;
      this.userinfo = res.data.data
   },
   methods: {
        // file 就是选择的文件对象
       async afterRead(file) {
      // 此时可以自行将文件上传至服务器
           console.log(file);
           // 上传需要用 FormData 的方式
           const fd=new FormData();
           fd.append('file',file.file);
           const res=await uploadFileAPL(fd)
           // 传进入的参数是一个 FormData 对象
           console.log(res)
        //    判断文件是否真的上传成功
           if(res.data.message==="文件上传成功"){
            //    获取图片地址
               const imgUrl=res.data.data.url;
            //    把新的图片地址，更新到用户信息中
               const qwe=await userUpdateByIdAPL(this.$route.query.id,{
                   head_img:imgUrl,
               })
            //    更新头像的展示
               this.userinfo.head_img=requser.defaults.baseURL+qwe.data.data.head_img;
               this.$toast.success("头像更换成功")
           }
           
        },
        // 更新用户
        async nicknameFn() {
          // console.log("666666666666,你点了确定按钮");
          // 获取输入框的用户昵称
          if (this.nicknameTemp === "") return this.$notify("请输入昵称，不能为空");
          // 发送请求更新用户昵称
          const res = await userUpdateByIdAPL(this.$route.query.id, {
            nickname: this.nicknameTemp,
          });
          // console.log(res);
          this.userinfo.nickname = res.data.data.nickname;
          this.$toast.success('昵称更新成功')
        },
        // 修改用户密码
        passwordFn() {
          console.log("确认修改密码");
        },
        async beforeClose(action, done){
      if(action==="confirm"){
        if(this.passwordOld===this.userinfo.password&&
        /^[a-zA-Z0-9~!@#$%^&*_+=-]{3,18}$/.test(this.passwordNew))
        {
           done();
           const res = await userUpdateByIdAPL(this.$route.query.id,{
             password:this.passwordNew
           });
           if(res.data.message==="修改成功"){
             // 由于页面没有刷新，所以修改后的密码也要做一下数据的同步
             this.userinfo.password=this.passwordNew;
             this.$toast.success("密码修改成功");
           }
        }else{
          done(false);
          // 轻提示
          this.$toast.fail("原密码输入错误");
        }
      }else{
        // 关闭弹窗
        done();
      }
        },
        // 编辑性别
        async genderFn(item) {
          // console.log("你点击了选项", item);
          const res = await userUpdateByIdAPL(this.$route.query.id, {
            gender: item.gender,
          });
          console.log(res);
          if (res.data.message === "修改成功") {
            // 轻提示
            this.$toast.success("性别更新成功");
            // 不刷新页面，还要同步一下视图的数据
            this.userinfo.gender = res.data.data.gender;
          }
        }
       
   }
}
</script>

<style lang="less" scoped>
.avatar{
    height:200px;
    background-color: rgb(201, 199, 199);
    display: flex;
    justify-content: center;
    align-items: center;
    .avatar-img{
        height:100px;
        width: 100px;
    }
}
// 把 van-uploader 通过定位盖到图片上
.van-uploader {
  position: absolute;
  opacity: 0;
}

</style>